<?php
/*
 * file_php - the PHP file operation class Author: <RamonQLee> Published:
 * 20121221 file_php is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. Usage: Examples:
 */

// require_once ('rss_php.php');
require_once 'RSS/feed.class.php';
require_once 'magpierss-0.72/rss_fetch.inc';
require_once 'rss_php.v1/rss_php.php';

define("kLoadRssException", "LoadRssException", TRUE);

class file_php
{
    //
    var $mFileHandle = "";

    var $mFileName = "";

    /**
     * append string to file and return
     *
     * @param unknown_type $filename            
     * @param unknown_type $appendString            
     */
    public static function appendString ($filename, $appendString)
    {
        $file = fopen($filename, "a");
        fwrite($file, $appendString . "\r\n");
        fclose($file);
    }

    /**
     * write as as a file
     *
     * @param unknown_type $filename            
     * @param unknown_type $json            
     * @param unknown_type $dataMap            
     */
    public static function writeJson ($filename, $json, $dataMap = true, 
            $key = "data")
    {
        $file = new file_php($filename);
        $file->open();
        if ($dataMap) {
            $file->write("{\"$key\":");
        }
        $file->write($json);
        if ($dataMap) {
            $file->write("}");
        }
        $file->close();
    }

    public static function writeJsonUTF8 ($filename, $json, $dataMap = true, 
            $key = "data")
    {
        $file = new file_php($filename);
        $file->open();
        if ($dataMap) {
            $file->writeutf8("{\"$key\":");
        }
        $file->writeutf8($json);
        if ($dataMap) {
            $file->writeutf8("}");
        }
        $file->close();
    }

    /**
     * call google image api to search files
     */
    public static function getGoogleImagesJson ($queryString)
    {
        $url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&start=1&q=" .
                 $queryString;
        return file_php::getRemoteFile($url);
    }

    /**
     * ����json���
     *
     * @param unknown_type $queryString            
     * @param unknown_type $searchMaxNum            
     * @return string
     */
    public static function getGoogleImagesMaxJson ($queryString, 
            $searchMaxNum = 64)
    {
        $kSearchUnit = 8;
        $count = $searchMaxNum % $kSearchUnit;
        $count = ($searchMaxNum - $count) / $kSearchUnit;
        
        // minimun one time
        $count = (0 == $count) ? 1 : $count;
        $ImagesArray = array();
        for ($i = 0; $i < $count; $i ++) {
            $jsrc = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=" .
                     $kSearchUnit . "&q=" . $queryString . "&start=" .
                     $i * $kSearchUnit;
            $json = file_php::getRemoteFile($jsrc);
            $jset = json_decode($json, true);
            if (false == $jset || null == $jset) {
                break;
            }
            $images = $jset['responseData']['results'];
            $ImagesArray = array_merge($ImagesArray, $images);
        }
        
        return json_encode($ImagesArray);
    }

    /**
     * get remote file with socket
     */
    public static function getRemoteFile ($url)
    {
        // Create a stream
        $opts = array(
                'http' => array(
                        'method' => "GET",
                        'header' => "Accept-language: en\r\n" .
                                 "Cookie: foo=bar\r\n"
                )
        );
        
        $context = stream_context_create($opts);
        // Open the file using the HTTP headers set above
        $response = file_get_contents($url, false, $context);
        if (false != $response) {
            return $response;
        }
        
        // get the host name and url path
        $parsedUrl = parse_url($url);
        $host = $parsedUrl['host'];
        if (isset($parsedUrl['path'])) {
            $path = $parsedUrl['path'];
        } else {
            // the url is pointing to the host like http://www.mysite.com
            $path = '/';
        }
        
        if (isset($parsedUrl['query'])) {
            $path .= '?' . $parsedUrl['query'];
        }
        
        if (isset($parsedUrl['port'])) {
            $port = $parsedUrl['port'];
        } else {
            // most sites use port 80
            $port = '80';
        }
        
        $timeout = 100;
        // connect to the remote server
        $fp = fsockopen($host, '80', $errno, $errstr, $timeout);
        
        if (! $fp) {
            echo "Cannot retrieve $url";
        } else {
            // send the necessary headers to get the file
            fputs($fp, 
                    "GET $path HTTP/1.0\r\n" . "Host: $host\r\n" .
                             "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" .
                             "Accept: */*\r\n" .
                             "Accept-Language: en-us,en;q=0.5\r\n" .
                             "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" .
                             "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" .
                             "Referer: http://$host\r\n\r\n");
            
            // retrieve the response from the remote server
            while (false != ($line = fread($fp, 4096))) {
                $response .= $line;
            }
            
            fclose($fp);
            
            // strip the headers
            $pos = strpos($response, "\r\n\r\n");
            $response = substr($response, $pos + 4);
        }
        
        // return the file content
        return $response;
    }
    
    /* creates a compressed zip file */
    public static function create_zip ($files = array(), $destination = '', 
            $overwrite = false)
    {
        // if the zip file already exists and overwrite is false, return false
        if (file_exists($destination) && ! $overwrite) {
            return false;
        }
        // vars
        $valid_files = array();
        // if files were passed in...
        if (is_array($files)) {
            // cycle through each file
            foreach ($files as $file) {
                // make sure the file exists
                if (file_exists($file)) {
                    $valid_files[] = $file;
                }
            }
        }
        // if we have good files...
        if (count($valid_files)) {
            // create the archive
            $zip = new ZipArchive();
            if ($zip->open($destination, 
                    $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !==
                     true) {
                return false;
            }
            // add the files
            foreach ($valid_files as $file) {
                $zip->addFile($file, $file);
            }
            // debug
            // echo 'The zip archive contains ',$zip->numFiles,' files with a
            // status of ',$zip->status;
            
            // close the zip -- done!
            $zip->close();
            
            // check to make sure the file exists
            return file_exists($destination);
        } else {
            return false;
        }
    }
    // utility functions
    /**
     * return rss items or constant("kLoadRssException") when exception occurs
     *
     * @param unknown_type $url            
     *
     */
    public static function loadRssReturnItems ($url)
    {
        // load with the following order when exception occurs
        try {
            return file_php::loadRssWithFeed($url);
        } catch (Exception $e) {
            echo $e;
        }
        
        try {
            return file_php::loadRssWithRssPhp($url);
        } catch (Exception $e) {
            echo $e;
        }
        
        try {
            return file_php::loadRssWithMagpierss($url);
        } catch (Exception $e) {
            echo $e;
        }
        
        return constant("kLoadRssException");
    }

    /**
     * load rss file and return a parsed rss object
     *
     * @param unknown_type $filename            
     * @return rss
     */
    private static function loadRssWithFeed ($filename)
    {
        if (true) {
            $rss = Feed::loadRss($filename);
            return $rss->item;
        } else {
            $rss = new rss_php();
            $rss->load($filename);
            return $rss->getItems();
        }
    }

    /**
     * load with magpierss
     *
     * @param unknown_type $filename            
     * @return Ambigous <boolean, unknown, MagpieRSS, number, mixed>
     */
    private static function loadRssWithMagpierss ($filename)
    {
        $rss = fetch_rss($filename);
        return $rss->items;
    }

    private static function loadRssWithRssPhp ($url)
    {
        $rss = new rss_php();
        $rss->load($url);
        return $rss->getItems();
    }

    /**
     * Checks whether a file or directory exists
     *
     * @param
     *            filename the file or directory.
     * @return bool true if the file or directory specified by
     *         filename exists; false otherwise.
     *         </p>
     *         <p>
     *         This function will return false for symlinks pointing to
     *         non-existing
     *         files.
     *         </p>
     *         <p>
     *         This function returns false for files inaccessible due to safe
     *         mode restrictions. However these
     *         files still can be included if
     *         they are located in safe_mode_include_dir.
     *         </p>
     *         <p>
     */
    public static function file_exists ($filename)
    {
        return file_exists($filename);
    }

    /**
     * delete a file
     *
     * @param unknown_type $filename            
     * @return bool Returns true on success or false on failure.
     */
    public static function delete ($filename)
    {
        if ($filename && file_exists($filename)) {
            unlink($filename);
        }
    }
    
    // constructor
    public function file_php ($filename)
    {
        $this->mFileName = $filename;
    }
    
    // interface
    /**
     * ֻд���򿪲�����ļ������ݣ�����ļ������ڣ��򴴽����ļ���
     *
     * @param unknown_type $filename            
     * @return file handle when success,false when fail
     */
    public function open ()
    {
        if (! strlen($this->mFileName)) {
            return false;
        }
        return ($this->mFileHandle = fopen($this->mFileName, "w"));
    }

    public function write ($string)
    {
        if (! $this->mFileHandle) {
            return;
        }
        fwrite($this->mFileHandle, $string);
    }

    public function writeutf8 ($string)
    {
        if (! $this->mFileHandle) {
            return;
        }
        fwrite($this->mFileHandle, iconv('gbk', 'utf-8//IGNORE', $string));
    }

    public function close ()
    {
        if (! $this->mFileHandle) {
            return;
        }
        fclose($this->mFileHandle);
    }
}

?>